package com.rz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.admin.entity.AdminRole;
import com.rz.admin.entity.Role;
import com.rz.admin.entity.RoleResource;
import com.rz.admin.entity.vo.DeleteParam;
import com.rz.admin.mapper.RoleMapper;
import com.rz.admin.service.IRoleResService;
import com.rz.admin.service.IRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleService extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private IRoleResService roleResService;
    @Resource
    private AdminService adminService;
    @Resource
    private AdminRoleService adminRoleService;

    @Override
    public IPage<Role> getPage(Role role) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        List<Integer> mngID = adminService.getChildrenIds(role.getCrteAdminId());
        mngID.add(role.getCrteAdminId());
        queryWrapper.in("crte_admin_id",mngID);
        Page<Role> page = new Page<>(role.getPageNo(),role.getPageSize());
        return page(page,queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean batchDelete(DeleteParam deleteParam) {
        deleteParam.getIds().forEach(roleId-> roleResService.deleteByRoleId(roleId));
        return removeByIds(deleteParam.getIds());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveRoleRes(Role role) {
        if(role.getId()==null){
            role.setCrteTime(LocalDateTime.now());
        }
        saveOrUpdate(role);
        roleResService.deleteByRoleId(role.getId());
        List<RoleResource>  roleResList = new ArrayList<>();
        role.getResInfo().forEach(resInfo-> roleResList.add(new RoleResource(role.getId(),resInfo.getResId(),resInfo.getLeaf())));
        return roleResService.saveBatch(roleResList);
    }

    @Override
    public List<RoleResource> getResByRoleId(Integer roleId) {
        return roleResService.getByRoleId(new ArrayList<Integer>(){{add(roleId);}});
    }

    @Override
    public List<Role> getByCrteAdminId(Integer adminId) {
        if(adminId.equals(1)){
            return list();
        }else{
            return new ArrayList<>(adminRoleService.getRolesByAdminId(adminId));
        }
    }
}
